package com.k12.admim.service.impl;

import com.k12.admim.model.entity.sys.SysPost;
import com.k12.admim.model.vo.sys.SysPostVo;
import com.k12.admim.rpc.UserFeignClient;
import com.k12.admim.service.OperatorPostService;
import com.k12.common.model.resp.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OperatorPostServiceImpl implements OperatorPostService {

    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public List<SysPost> listPost(SysPostVo post) {
        return userFeignClient.getAllPost(post);
    }

    @Override
    public boolean checkPostNameUnique(SysPostVo post) {
        Long postId = post.getPostId() == null ? -1L : post.getPostId();
        SysPost info = userFeignClient.checkPostNameUnique(post.getPostName(), post.getTenantId());
        if (info != null && info.getPostId().longValue() != postId.longValue()) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkPostCodeUnique(SysPostVo post) {
        Long postId = post.getPostId() == null ? -1L : post.getPostId();
        SysPost info = userFeignClient.checkPostCodeUnique(post.getPostCode(), post.getTenantId());
        if (info != null && info.getPostId().longValue() != postId.longValue()) {
            return false;
        }
        return true;
    }

    @Override
    public boolean insertPost(SysPostVo post) {
         userFeignClient.insertPost(post);
        return true;
    }

    @Override
    public boolean updatePost(SysPostVo post) {
        userFeignClient.updatePost(post);
        return true;
    }

    @Override
    public R deletePostByIds(Long[] postIds,String tenantId) {
        for (Long postId : postIds)
        {
            SysPost post = selectPostById(postId,tenantId);
            if (countUserPostById(postId,tenantId) > 0)
            {
                return R.failed(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
        int i = userFeignClient.deletePostByIds(postIds,tenantId);
        if (i > 0){
            return R.success();
        }else{
            return R.failed("删除失败");
        }
    }

    @Override
    public SysPost selectPostById(Long postId,String tenantId) {
        return userFeignClient.selectPostById(postId,tenantId);
    }

    public int countUserPostById(Long postId,String tenantId) {
        return userFeignClient.countUserPostById(postId,tenantId);
    }
}
